<template>
  <el-dialog :modelValue="show" title="总代信息" top="10vh" :close-on-click-modal="false" :close-on-press-escape="false"
    @close="cancel">
    <el-form :model="data.addQuery" class="dialogMaxHeight" ref="addQuery" :rules="data.rules" status-icon
      :validate-on-rule-change="false" :scroll-to-error="true">
      <form-item title="总代类型" value="is_multi_currency">
        <el-radio-group v-model="data.addQuery.is_multi_currency" @change="chooseType" size="large"
          :disabled="data.addQuery.id ? true : false">
          <el-radio-button label="正常总代" :value="0" />
          <el-radio-button label="多货币总代" :value="1" />
        </el-radio-group>
      </form-item>
      <form-item title="总代昵称" :pass="true" value="operator_name">
        <el-input clearable placeholder="请输入" :disabled="data.addQuery.id != 0" maxlength="20"
          v-model="data.addQuery.operator_name" />
      </form-item>
      <form-item title="后台账号" :pass="true" value="username">
        <el-input clearable placeholder="请输入" autocomplete="off" :disabled="data.addQuery.id ? true : false" maxlength="20"
          v-model="data.addQuery.username" />
      </form-item>
      <form-item title="后台密码" :pass="data.rules.password[0].required" value="password">
        <el-input clearable placeholder="请输入" autocomplete="new-password" type="password"
          v-model="data.addQuery.password" />
      </form-item>
      <form-item title="GGR分成比例" :pass="true" value="slot_ratio">
        <el-input clearable type="number" oninput="if(value>100 || value<0) value=0"
          v-model.number="data.addQuery.slot_ratio" placeholder="请输入0-100数字">
          <template #append>%</template>
        </el-input>
      </form-item>
      <form-item title="地区选择" :pass="true" value="area" v-show="data.addQuery.is_multi_currency ? true : false">
        <el-select v-model="data.addQuery.area" filterable placeholder="请选择">
          <el-option v-for="(item, index) in COUNTRY" :key="index" :label="item.label" :value="item.value" />
        </el-select>
        <span class="tipsText">(推广平台的地区,下拉搜索选择)</span>
      </form-item>
      <form-item title="API接入模式" :pass="true" value="api_type" v-show="data.addQuery.is_multi_currency ? true : false">
        <el-select v-model="data.addQuery.api_type" placeholder="请选择" :disabled="data.addQuery.id ? true : false">
          <el-option v-for="item in APITYPE" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </form-item>
      <form-item title="结算货币" :pass="true" value="currencyList" v-show="data.addQuery.is_multi_currency ? true : false">
        <el-select class="imWidth100" v-model="data.addQuery.currencyList" filterable multiple placeholder="请选择">
          <el-option v-for="(item, index) in indexStore.currentArray" :key="index"
            :label="item.label + ' (' + item.type + ')' + '-' + item.remark" :value="item.value" />
        </el-select>
        <span class="tipsText">(选择的货币游戏内即显示对应的货币符号)</span>
      </form-item>
      <form-item title="总代游戏" value="game_ids" :pass="true" style="height: auto;position: relative;"
        v-show="data.addQuery.is_multi_currency ? true : false">
        <el-button :type="data.addQuery.gameList.length != indexStore.gameArray.length ? 'danger' : 'info'"
          @click="chooseGame()">{{ data.addQuery.gameList.length != indexStore.gameArray.length ? '全选游戏' : '取消全选'
          }}</el-button>
        <el-checkbox-group v-model="data.addQuery.gameList">
          <el-checkbox class="margin5" v-for="(item, index) in indexStore.gameArray" :key="index" :value="item.value"
            border>
            <div class="flexCenter">
              <img class="game-icon" :src="selectToLabel(GAMEICON, item.value)" alt="">
              {{ selectToLabel(indexStore.gameArray, item.value) }}
            </div>
          </el-checkbox>
        </el-checkbox-group>
      </form-item>
      <form-item title="总代秘钥" value="key" :pass="data.rules.key[0].required"
        v-show="data.addQuery.is_multi_currency ? true : false">
        <div class="inputAndBtn">
          <el-input class="width320" clearable placeholder="请输入" v-model="data.addQuery.key" />
          <el-button class="marginL5" size="small" type="primary" @click="autoKey">生成秘钥</el-button>
          <span class="tipsText">(非必填-该秘钥为总代填写，总代账号只做展示和修改)</span>
        </div>
      </form-item>
      <form-item title="第三方接口域名" value="domain_name" :pass="data.rules.domain_name[0].required"
        v-show="data.addQuery.is_multi_currency ? true : false">
        <el-input class="width320" clearable placeholder="请输入" v-model="data.addQuery.domain_name">
          <template #prepend>https://</template>
        </el-input>
        <span class="tipsText">({{ t('des_23') }})</span>
      </form-item>
      <form-item title="联系方式：" value="contact">
        <el-input clearable placeholder="请输入" v-model="data.addQuery.contact" />
      </form-item>
      <form-item title="备注：" value="remark">
        <el-input clearable maxlength="200" type="textarea" :checkedItems="3" placeholder="请输入"
          v-model="data.addQuery.remark" />
      </form-item>
      <form-item title="是否验证谷歌验证码" value="google_check">
        <el-radio-group v-model="data.addQuery.google_check" size="large" @change="chooseGoogle">
          <el-radio-button label="不验证" :value="0" />
          <el-radio-button label="验证" :value="1" />
        </el-radio-group>
      </form-item>
      <form-item title="谷歌Url" value="google_url" v-show="data.addQuery.google_check" style="height:auto">
        <QrcodeVue :value="data.addQuery.google_url" :size="140" fg-color="#000" />
        <el-input class="width100 marginT5" v-model="data.addQuery.google_url" type="text" readonly />
      </form-item>
      <form-item title="谷歌秘钥" value="google_secret" v-show="data.addQuery.google_check">
        <el-input class="marginT5" v-model="data.addQuery.google_secret" type="text" readonly />
      </form-item>
      <form-item title="谷歌验证码" :pass="props.checkedItem.google_check || data.addQuery.google_check ? true : false"
        value="google_code" v-show="props.checkedItem.google_check || data.addQuery.google_check">
        <el-input class="marginT5" v-model="data.addQuery.google_code" type="text" placeholder="请输入谷歌验证码" />
      </form-item>
      <form-item title="IP白名单" value="white_ip">
        <el-input clearable maxlength="200" type="textarea" :checkedItems="3" placeholder="请输入IP白名单,多个IP用( ; )分开"
          v-model="data.addQuery.white_ip" />
      </form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, nextTick } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import QrcodeVue from 'qrcode.vue'
import FormItem from '@/components/FormItem/FormItem.vue'
import { ElMessage } from 'element-plus'
import { postSystemAddOperator, putSystemChangeOperator, postSystemFandKey, googleKey } from '@/api/merchant'
import { APITYPE, GAMEICON } from '@/config/eunm'
import { COUNTRY } from '@/config/country'
import { selectToLabel, removeDomain, domainVerification } from '@/utils/index'
import { useStore } from '@/stores/index'
const indexStore = useStore()
import { useI18n } from 'vue-i18n'
const { t } = useI18n()

const props = defineProps({
  show: Boolean,
  checkedItem: {
    type: Object,
    default: () => { }
  }
})

const data = reactive({
  addQuery: {
    id: 0, // 总代id
    operator_name: '', //总代名称
    username: '', // 后台账号
    password: '', // 后台密码
    contact: '', //联系方式
    remark: '', // 备注
    white_ip: '', // IP白名单
    google_check: 0, // IP白名单
    google_url: '', // 谷歌二维码
    google_secret: '', // 谷歌二维码
    google_code: '', // 谷歌验证码
    slot_ratio: null, // slot 分成比例 百分比
    hundred_ratio: null,
    fish_ratio: null,
    street_ratio: null,
    // 多货币
    is_multi_currency: 0, // 0普通 1多货币
    currency_ids: '', // 币种
    currencyList: [] as any[], // 商户币种
    domain_name: '', // 接口域名
    key: '', // 秘钥
    area: '', //地区选择
    agent_request_url: '',// 商户请求地址
    api_type: 0, //  0单一 1转账
    game_ids: '', //  默认游戏ID
    gameList: [] as any[], // 商户游戏
  },
  rules: {
    operator_name: [{ required: true, message: '请输入', trigger: 'blur' }],
    username: [{ required: true, message: '请选择', trigger: 'change' }],
    password: [
      { required: true, message: '请输入', trigger: 'blur' },
      { min: 6, max: 20, message: '请输入6-20位字符', trigger: 'blur' }
    ],
    currency_ids: [{ required: false, message: '请输入', trigger: 'blur' }],
    domain_name: [{ required: false, message: '请输入', trigger: 'blur' }],
    key: [{ required: false, message: '请输入', trigger: 'blur' }],
    area: [{ required: false, message: '请输入', trigger: 'blur' }],
    slot_ratio: [{ required: true, message: '请输入0-100数字', trigger: 'blur' }],
  },
})

watch(
  () => props.checkedItem,
  async (val) => {
    await nextTick
    addQuery.value!.resetFields()
    val.domain_name = removeDomain(val.domain_name)
    Object.assign(data.addQuery, val)
    chooseType(val.is_multi_currency)
    data.rules.password[0].required = data.addQuery.id ? false : true
    data.rules.key[0].required = data.addQuery.key ? true : false
    data.rules.domain_name[0].required = data.addQuery.domain_name ? true : false
  }
)

const addQuery = ref<FormInstance>()
const emit = defineEmits(['cancel'])

// 保存
const save = async () => {
  if (!addQuery.value) return
  await addQuery.value.validate(async (valid, fields) => {
    if (valid) {
      let query = JSON.parse(JSON.stringify(data.addQuery))
      if (props.checkedItem.google_check && !query.google_code) {
        return ElMessage({ message: '请输入谷歌验证码', type: 'error' })
      } else if (!props.checkedItem.google_check && !query.google_check) {
        query.google_code = 0
        query.google_url = ''
        query.google_secret = ''
      } else if (query.google_check && !query.google_code) {
        return ElMessage({ message: '请输入谷歌验证码', type: 'error' })
      } else if (query.google_code) {
        query.google_code = Number(query.google_code)
      }
      query.hundred_ratio = query.fish_ratio = query.street_ratio = query.slot_ratio

      // 多货币总代
      if (query.is_multi_currency) {
        query.game_ids = query.gameList.join(',')
        if (!query.game_ids) {
          return ElMessage.error('请选择总代游戏')
        }
        query.currency_ids = query.currencyList.join(',')
        if (!query.currency_ids) {
          return ElMessage.error('请选择总代货币')
        }
      } else {
        query.currency_ids = ''
        query.game_ids = ''
      }
      // 域名格式校验
      query.domain_name = domainVerification(query.domain_name)
      const res = query.id ? await putSystemChangeOperator(query) : await postSystemAddOperator(query)
      if (res.code) {
        ElMessage({
          message: '操作成功',
          type: 'success'
        })
        indexStore.getOperator() //总代汇总
        query = null
        cancel(true)
      }
    }
  })
}

// 选择总代类型
const chooseType = async (value: any) => {
  if (value) {
    data.rules.currency_ids[0].required = true
    data.rules.area[0].required = true
  } else {
    data.rules.currency_ids[0].required = false
    data.rules.area[0].required = false
  }
}

// 生成秘钥
const autoKey = async () => {
  let res = await postSystemFandKey({})
  data.addQuery.key = res.data
}

// 游戏配置
const chooseGame = () => {
  if (data.addQuery.gameList.length != indexStore.gameArray.length) {
    data.addQuery.gameList = []
    indexStore.gameArray.forEach((item: any) => {
      return data.addQuery.gameList.push(Number(item.value))
    })
  } else {
    data.addQuery.gameList = []
  }
}

// 是否开启谷歌验证码
const chooseGoogle = async (val: number) => {
  if (val) {
    if (!data.addQuery.operator_name) {
      data.addQuery.google_check = 0
      return ElMessage({
        type: 'error',
        message: '请输入总代名称'
      })
    } else {
      if (data.addQuery.google_url) return
      let res = await googleKey({ username: data.addQuery.operator_name })
      data.addQuery.google_url = res.data.google_url
      data.addQuery.google_secret = res.data.google_secret
    }
  }
}

// 取消
const cancel = async (val?: Boolean) => {
  emit('cancel', val)
  addQuery.value!.resetFields()
  data.addQuery = {
    id: 0, // 总代id
    operator_name: '', //总代名称
    username: '', // 后台账号
    password: '', // 后台密码
    contact: '', //联系方式
    remark: '', // 备注
    white_ip: '', // IP白名单
    google_check: 0, // IP白名单
    google_url: '', // 谷歌二维码
    google_secret: '', // 谷歌二维码
    google_code: '', // 谷歌二维码
    slot_ratio: null, // slot 分成比例 百分比
    hundred_ratio: null,
    fish_ratio: null,
    street_ratio: null,
    // 多货币
    is_multi_currency: 0, // 0普通 1多货币
    currency_ids: '', // 币种
    currencyList: [] as any[], // 商户币种
    domain_name: '', // 接口域名
    key: '', // 秘钥
    area: '',
    agent_request_url: '',// 商户请求地址
    api_type: 0, //  0单一 1转账
    game_ids: '', //  默认游戏ID
    gameList: [] as any[], // 商户游戏
  }
}
</script>
<style scoped lang="scss">
.inputAndBtn {
  display: flex;
  align-items: center;
}
</style>
